package getGaokaoXuankeData.controller;

import io.github.jonathanlink.PDFLayoutTextStripper;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.*;

/**
 * 1.实现将PDF转换为word
 * 2.实现将PDF导出图片
 */
public class PdfToWord {
    public static void main(String[] args) throws IOException {
        //pdf2word_pic();
        readPdf();
    }

    //读取PDF文件
    private static void readPdf() throws IOException {
        String filePath = "F:\\file\\202007\\PDF2word\\test001.pdf";
        PDFParser pdfParser = new PDFParser(new org.apache.pdfbox.io.RandomAccessFile(new File(filePath), "rw"));
        pdfParser.parse();
        PDDocument pdDocument = pdfParser.getPDDocument();
        //new PDFTextStripper().
        String text = new PDFTextStripper().getText(pdDocument);
        pdDocument.close();
        System.out.println(text);

    }
    //PDF有图片版转word
    private static void pdf2html(){
//        PdfDocument pdf = new PdfDocument("test.pdf");
//        pdf.saveToFile("ToHTML.html", FileFormat.HTML);
    }
    //PDF有图片版转word,并且要保持原有的格式
    private static void pdf2word_pic() throws IOException {
        String pdfFile_path = "F:\\file\\202007\\PDF2word\\z06.pdf";
        File pdfFile_out = new File("F:\\"+System.currentTimeMillis()+".pdf");
        if (!pdfFile_out.exists()){
            pdfFile_out.createNewFile();
        }
        // 待解析PDF
        File pdfFile = new File(pdfFile_path);
        PDDocument document = null;
        PDDocument document_out = null;
        try {
            document = PDDocument.load(pdfFile);
            System.out.println(document);
            //document_out = PDDocument.load(pdfFile_out);
        } catch (IOException e) {
            e.printStackTrace();
        }





    }
    //PDF纯文字版转word
    private static void pdf2word_word(){
        try {
            String pdfFile = "F:\\file\\202007\\PDF2word\\z06.pdf";
            PDDocument doc = PDDocument.load(new File(pdfFile));
            int pagenumber = doc.getNumberOfPages();
            pdfFile = pdfFile.substring(0, pdfFile.lastIndexOf("."));
            String fileName = pdfFile + ".doc";
            File file = new File(fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(fileName);
            Writer writer = new OutputStreamWriter(fos, "UTF-8");
            PDFTextStripper stripper = new PDFTextStripper();
            stripper.setSortByPosition(true);// 排序
            stripper.setStartPage(1);// 设置转换的开始页
            stripper.setEndPage(pagenumber);// 设置转换的结束页
            stripper.writeText(doc, writer);
            writer.close();
            doc.close();
            System.out.println("pdf转换word成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
